package com.itheima.practice02;
//Map的两种遍历

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;


public class MapTest02 {
    public static void main(String[] args) {

        Map<String, Integer> map = new TreeMap();

        map.put("八戒", 1880);
        map.put("三藏", 31);
        map.put("悟空", 5000);
        map.put("沙和尚", 2300);
        System.out.println(map);

        // get(Object key)根据键获取值
        Integer integer = map.get("三藏");
        System.out.println(integer);

        // 1. 通过keySet()遍历  keySet()获取所有键的集合
        Set<String> strings = map.keySet();
        //1)用迭代器遍历
        Iterator<String> iterator = strings.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);
        }
        System.out.println("=======================");
        //2)用增强For遍历
        for (String string : strings) {
            System.out.println(string);
        }
        System.out.println("=======================");

        //2.用entrySet()进行遍历
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        //1)用迭代器进行遍历
        Iterator<Map.Entry<String, Integer>> iterator1 = entries.iterator();
        while (iterator1.hasNext()) {
            String key = iterator1.next().getKey();
            Integer value = map.get(key);
            System.out.println(key + "=" + value);
        }
        System.out.println("=======================");
        //2)用增强for进行遍历
        for (Map.Entry<String, Integer> entry : entries) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key + "=" + value);
        }
        System.out.println("---------------------------------");

        //3.foreach()遍历
        map.forEach((name, age) -> {
            System.out.println(name + "=" + age);
        });
    }
}
